// ignore_for_file: file_names, slash_for_doc_comments

import 'dart:async';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:mybase/base/config/DeaultPageConfig.dart';
import 'package:mybase/base/tool/empty/FFEmpty.dart';

/**图片util */
class FFImageUtil {
  static String utilDefaultNetImage =
      "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.jj20.com%2Fup%2Fallimg%2Ftp09%2F210Q6133S9A22-0-lp.jpg&refer=http%3A%2F%2Fimg.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1663494430&t=2cf3d8343ba0621295621ea05e83626e";

  static Widget _failWidget({
    Widget? defaultWidget,
  }) {
    if (defaultWidget != null) {
      return defaultWidget ?? Container();
    }

    if (DeaultPageConfig().ffImageDefault != null) {
      return DeaultPageConfig().ffImageDefault ?? Container();
    }

    return Center(
      child: Container(
        color: Colors.transparent,
      ),
    );
  }

  static Widget _placeholderWidget() {
    return Container(
      alignment: Alignment.center,
      color: Colors.transparent,
    );
  }

  /**
   * 网络图片
   */
  static Widget utilNetworkImage(
    String url, {
    BoxFit? fit = BoxFit.cover,
    Widget? defaultWidget,
    Function()? loadErr,
  }) {
    if (FFEmpty.stringIsEmpty(url) || !url.startsWith("http")) {
      return _failWidget(defaultWidget: defaultWidget);
    }

    try {
      return CachedNetworkImage(
        fit: fit,
        imageUrl: url,
        placeholder: (context, url) {
          return _placeholderWidget();
        },
        errorWidget: (context, url, error) {
          if (loadErr != null) {
            loadErr!();
          }
          return _failWidget(defaultWidget: defaultWidget);
        },
      );
    } catch (e) {
      print("FFImageUtil load image error");
    }

    return _failWidget(defaultWidget: defaultWidget);
  }

  /**
   * 网络图片
   */
  static Widget utilNetworkImage_imageBuilder(
    String url, {
    BoxFit? fit = BoxFit.cover,
    Widget Function(BuildContext, ImageProvider<Object>)? imageBuilder,
  }) {
    if (FFEmpty.stringIsEmpty(url) || !url.startsWith("http")) {
      return _failWidget();
    }

    try {
      return CachedNetworkImage(
        fit: fit,
        imageUrl: url,
        placeholder: (context, url) {
          return _placeholderWidget();
        },
        errorWidget: (context, url, error) {
          return _failWidget();
        },
        imageBuilder: imageBuilder,
      );
    } catch (e) {
      print("FFImageUtil load image error");
    }

    return _failWidget();
  }
}
